package com.cip.master.dao.impl;

import java.util.List;

import com.cip.admin.dao.impl.CipHibernateDAOSupport;

import com.cip.master.model.Academic;
import com.cip.master.model.ClassYear;
import com.cip.master.model.Section;
import com.cip.master.model.Subject;
import com.cip.admin.model.User;
import com.cip.master.model.Result;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.cip.master.dao.ResultDAO;
import com.cip.master.model.Examination;
import com.cip.master.model.Result;


public class ResultDAOImpl extends CipHibernateDAOSupport implements ResultDAO {

	public List<Result> getAllResults() throws Exception {
		HibernateTemplate hibernateTemplate = getCipHibernateTemplate();	
	    List<Result> results = hibernateTemplate.loadAll(Result.class);
		return results;
	}
	
	public List<Result> getResultsByCandidate(String academicYear, String classYear,
			String sectionName, String examName,String studentId) throws Exception{
//		 Result(ClassYear classYear,Academic academic,Subject subject,Examination examination,Section section,int mark,User user,int avgMark)
		String query="select new Result(result.classYear,result.academic,result.subject,result.examination,result.section,result.mark,result.user," +
				"(select (avg(inResult.mark)) from Result as inResult where inResult.subject=result.subject and inResult.academic='"+academicYear+"' " +
						"and inResult.classYear='"+classYear+"'"+" and inResult.section='"+sectionName+"' and inResult.examination='"+examName+"' )) " +
				"from Result as result where "
						+"result.classYear='"+classYear+"'"+" and result.section='"+sectionName+"'"
						+"and result.examination='"+examName+"' and result.user='"+studentId+"' group by result.subject";
		//System.out.println("query---------->"+query);
		
		/*org.hibernate.Query hibernateQuery = null;
		Session session = getSession();


		session = getSession();
		hibernateQuery = session.createQuery(query);
        
		List<Result> results = hibernateQuery.list();
*/		List<Result> results = getCipHibernateTemplate().find(query);
		System.out.println("in result dao====>"+results.size());
		return results;
	}
	
	public List<Result> getResultsBySearch(String academicYear, String classYear,
			String sectionName, String examName) throws Exception{
		String query="select result from Result as result where result.academic='"+academicYear+"'"
						+"and result.classYear='"+classYear+"'"+" and result.section='"+sectionName+"'"
						+"and result.examination='"+examName+"' group by result.user" ;
		List<Result> results = getCipHibernateTemplate().find(query);
		System.out.println("in result dao====>"+results.size());
		return results;
	}
	
	public Result saveOrUpdateResult(Result result) throws Exception {
		getHibernateTemplate().saveOrUpdate(result);
		return result;
	}
	
}
